﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using CardLogistics.Model.CardMaking;
using System.Data.OracleClient;

namespace CardLogistics.DAL.CardMaking
{
    /// <summary>
    /// 卡片制作_离盒操作数据访问类
    /// </summary>
    public partial class CardMaking_CardSeparateData
    {
        #region 查询
        /// <summary>
        /// 根据条件查询相应的表的字段
        /// </summary>
        /// <param name="StrWhere">查询条件</param>
        /// <param name="StrFields">要查询的字段</param>
        /// <returns>填充完数据的DataTable</returns>
        public DataTable GetList(string StrWhere, string StrFields)
        {
            return CommonData.GetListOrderBy(StrWhere, "v_CardMaking_CardSeparate", StrFields, "ID", 0);
        }

        /// <summary>
        /// 根据编号查询基本信息
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>填充完数据的DataTable</returns>
        public DataTable GetInfoById(string id)
        {
            return GetList(" ID = '" + id + "' ", "*");
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public CardMaking_CardSeparate GetModel(string rId)
        {
            CardMaking_CardSeparate model = new CardMaking_CardSeparate();
            DataRow row = GetInfoById(rId).Rows[0];
            if (row != null)
            {
                if (row["ID"] != null && row["ID"].ToString() != "")
                {
                    model.ID = row["ID"].ToString();
                }
                if (row["SEPARATENO"] != null && row["SEPARATENO"].ToString() != "")
                {
                    model.Separateno = row["SEPARATENO"].ToString();
                }
                if (row["SEPARATEUSER"] != null && row["SEPARATEUSER"].ToString() != "")
                {
                    model.Separateuser = row["SEPARATEUSER"].ToString();
                }
                if (row["SEPARATEDATE"] != null && row["SEPARATEDATE"].ToString() != "")
                {
                    model.Separatedate = DateTime.Parse(row["SEPARATEDATE"].ToString());
                }
                if (row["REMARKS"] != null && row["REMARKS"].ToString() != "")
                {
                    model.REMARKS = row["REMARKS"].ToString();
                }
                if (row["LASTUPDATEUSER"] != null && row["LASTUPDATEUSER"].ToString() != "")
                {
                    model.LASTUPDATEUSER = row["LASTUPDATEUSER"].ToString();
                }
                if (row["LASTUPDATEDATE"] != null && row["LASTUPDATEDATE"].ToString() != "")
                {
                    model.LASTUPDATEDATE = DateTime.Parse(row["LASTUPDATEDATE"].ToString());
                }
                if (row["ADDTIME"] != null && row["ADDTIME"].ToString() != "")
                {
                    model.ADDTIME = DateTime.Parse(row["ADDTIME"].ToString());
                }
                if (row["ISSUBMIT"] != null && row["ISSUBMIT"].ToString() != "")
                {
                    model.ISSUBMIT = decimal.Parse(row["ISSUBMIT"].ToString());
                }
            }
            return model;
        }
        #endregion

        #region  重载新增信息
        /// <summary>
        /// 重载新增信息
        /// </summary>
        /// <param name="model">实体类</param>
        /// <returns>返回插入数据的编号</returns>
        public string Add(CardMaking_CardSeparate model, string FileValue)
        {
            string StrOutPar = string.Empty;
            int val = 0;
            string sqlConn = DbHelperSQL.ConnectionString;
            using (OracleConnection conn = new OracleConnection(sqlConn))
            {
                conn.Open();
                OracleCommand cmd = new OracleCommand();
                cmd.Connection = conn;
                OracleTransaction tx = conn.BeginTransaction();
                cmd.Transaction = tx;

                string[] split = FileValue.Split(';');//以分号分隔
                int count = split.Length; //计算行数
                string separateId = System.Guid.NewGuid().ToString();//主键ID
                try
                {
                    StringBuilder strSql = new StringBuilder(" begin ");
                    for (int i = 0; i < count; i++)
                    {
                        string BOXNO = split[i].Split('|')[0];
                        string CARDNO = split[i].Split('|')[1];
                        string STARTNO = split[i].Split('|')[2];
                        string ENDNO = split[i].Split('|')[3];
                        string DUENUMBER = split[i].Split('|')[4];
                        string ACTUALNUMBER = split[i].Split('|')[5];
                        string MISSINGCARDNO = split[i].Split('|')[6];

                        strSql.Append("insert into CardMaking_CardSeparate_Detail");
                        strSql.Append("(SEPARATEID,BOXNO,CARDNO,STARTNO,ENDNO,DUENUMBER,ACTUALNUMBER,MISSINGCARDNO)");
                        strSql.Append(" values(");
                        strSql.Append("'" + separateId + "',");
                        strSql.Append("" + BOXNO + "," + CARDNO + ", " + STARTNO + ", " + ENDNO + ", " + DUENUMBER + ", " + ACTUALNUMBER + "," + MISSINGCARDNO);
                        strSql.Append(");");
                    }
                    strSql.Append(" end; ");
                    if (!String.IsNullOrEmpty(strSql.ToString()))
                    {
                        cmd.CommandText = strSql.ToString();
                        val += cmd.ExecuteNonQuery();
                    }
                    OracleParameter[] parameters = {
					new OracleParameter("varOut", OracleType.VarChar,200),
					new OracleParameter("vSEPARATENO", OracleType.VarChar,50),
					new OracleParameter("vSEPARATEUSER", OracleType.VarChar,50),
					new OracleParameter("vSEPARATEDATE", OracleType.DateTime),
					new OracleParameter("vREMARKS", OracleType.NVarChar),
					new OracleParameter("vLASTUPDATEUSER", OracleType.VarChar,50),
					new OracleParameter("vLASTUPDATEDATE", OracleType.DateTime),
					new OracleParameter("vADDTIME", OracleType.DateTime),
					new OracleParameter("vISSUBMIT", OracleType.Number,4),
                    new OracleParameter("VID", OracleType.VarChar,50)};
                    parameters[0].Direction = ParameterDirection.Output;
                    parameters[1].Value = model.Separateno;
                    parameters[2].Value = model.Separateuser;
                    parameters[3].Value = model.Separatedate;
                    parameters[4].Value = model.REMARKS;
                    parameters[5].Value = model.LASTUPDATEUSER;
                    parameters[6].Value = model.LASTUPDATEDATE;
                    parameters[7].Value = model.ADDTIME;
                    parameters[8].Value = model.ISSUBMIT;
                    parameters[9].Value = separateId;

                    StrOutPar = DbHelperSQL.RunProcedure("P_CardMaking_CardSeparate_Add", parameters, parameters[0]).ToString();
                    if (StrOutPar.Split(',')[0] == "ok")
                    {
                        tx.Commit();
                    }
                    else
                        tx.Rollback();
                    return StrOutPar;
                }
                catch (System.Data.OracleClient.OracleException e)
                {

                    tx.Rollback();
                    throw new Exception(e.Message);
                }
                finally
                {
                    if (conn.State != ConnectionState.Closed)
                    {
                        conn.Close();
                    }
                }
            }
        }
        #endregion


        #region 重载修改信息
        /// <summary>
        /// 重载修改信息
        /// </summary>
        /// <param name="model">实体类</param>
        /// <returns>返回插入数据的编号</returns>
        public string Update(CardMaking_CardSeparate model, string FileValue)
        {
            string StrOutPar = string.Empty;
            int val = 0;
            string sqlConn = DbHelperSQL.ConnectionString;
            using (OracleConnection conn = new OracleConnection(sqlConn))
            {
                conn.Open();
                OracleCommand cmd = new OracleCommand();
                cmd.Connection = conn;
                OracleTransaction tx = conn.BeginTransaction();
                cmd.Transaction = tx;

                string[] split = FileValue.Split(';');//以分号分隔
                int count = split.Length; //计算行数

                try
                {
                    StringBuilder strSql = new StringBuilder(" begin ");
                    strSql.Append(" delete from CardMaking_CardSeparate_Detail where SEPARATEID ='" + model.ID + "';");//删除已离盒明细
                    for (int i = 0; i < count; i++)
                    {
                        string BOXNO = split[i].Split('|')[0];
                        string CARDNO = split[i].Split('|')[1];
                        string STARTNO = split[i].Split('|')[2];
                        string ENDNO = split[i].Split('|')[3];
                        string DUENUMBER = split[i].Split('|')[4];
                        string ACTUALNUMBER = split[i].Split('|')[5];
                        string MISSINGCARDNO = split[i].Split('|')[6];

                        strSql.Append("insert into CardMaking_CardSeparate_Detail");
                        strSql.Append("(SEPARATEID,BOXNO,CARDNO,STARTNO,ENDNO,DUENUMBER,ACTUALNUMBER,MISSINGCARDNO)");
                        strSql.Append(" values(");
                        strSql.Append("'" + model.ID + "',");
                        strSql.Append("" + BOXNO + "," + CARDNO + ", " + STARTNO + ", " + ENDNO + ", " + DUENUMBER + ", " + ACTUALNUMBER + "," + MISSINGCARDNO);
                        strSql.Append(");");
                    }
                    strSql.Append(" end; ");
                    if (!String.IsNullOrEmpty(strSql.ToString()))
                    {
                        cmd.CommandText = strSql.ToString();
                        val += cmd.ExecuteNonQuery();
                    }
                    OracleParameter[] parameters = {
					new OracleParameter("vID", OracleType.VarChar,50),
				    new OracleParameter("vSEPARATENO", OracleType.VarChar,50),
					new OracleParameter("vSEPARATEUSER", OracleType.VarChar,50),
					new OracleParameter("vSEPARATEDATE", OracleType.DateTime),
					new OracleParameter("vREMARKS", OracleType.NVarChar),
					new OracleParameter("vLASTUPDATEUSER", OracleType.VarChar,50),
					new OracleParameter("vLASTUPDATEDATE", OracleType.DateTime),
					new OracleParameter("vADDTIME", OracleType.DateTime),
					new OracleParameter("vISSUBMIT", OracleType.Number,4),
                    new OracleParameter("varOut", OracleType.VarChar,50)};
                    parameters[0].Value = model.ID;
                    parameters[1].Value = model.Separateno;
                    parameters[2].Value = model.Separateuser;
                    parameters[3].Value = model.Separatedate;
                    parameters[4].Value = model.REMARKS;
                    parameters[5].Value = model.LASTUPDATEUSER;
                    parameters[6].Value = model.LASTUPDATEDATE;
                    parameters[7].Value = model.ADDTIME;
                    parameters[8].Value = model.ISSUBMIT;
                    parameters[9].Direction = ParameterDirection.Output;
                    StrOutPar = DbHelperSQL.RunProcedure("P_CardMaking_CardSeparate_Up", parameters, parameters[9]).ToString();

                    if (StrOutPar.Split(',')[0] == "ok")
                    {
                        tx.Commit();
                    }
                    else
                        tx.Rollback();
                    return StrOutPar;
                }
                catch (System.Data.OracleClient.OracleException e)
                {
                    tx.Rollback();
                    return StrOutPar;
                    throw new Exception(e.Message);
                }
                finally
                {
                    if (conn.State != ConnectionState.Closed)
                    {
                        conn.Close();
                    }
                }
            }
        }
        #endregion

        #region 删除
        /// <summary>
        /// 删除信息(同时删除白卡出库明细)
        /// </summary>
        /// <param name="id">删除信息的ID</param>
        /// <returns>删除成功返回True。否则返回false</returns>
        public string Delete(string id)
        {
            try
            {
                OracleParameter[] parameters = {
                        new OracleParameter("VarOut",  OracleType.VarChar,100),
					    new OracleParameter("vid",  OracleType.VarChar,50)
                };
                parameters[0].Direction = ParameterDirection.Output;
                parameters[1].Value = id;
                string StrOutPar = DbHelperSQL.RunProcedure("P_CardMaking_CardSeparate_Del", parameters, parameters[0]).ToString();
                return StrOutPar;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        /// <summary>
        /// 根据开始卡号、结束卡号判断离盒单号是否存在
        /// </summary>
        /// <param name="SpId">离盒单ID</param>
        /// <param name="startNO">开始卡号</param>
        /// <param name="endNO">结束卡号</param>
        /// <returns>已存在返回true 否则返回false</returns>
        public bool IsExisSpKu(string SpId, string startNo, string endNo)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(0) from cardmaking_cardseparate_detail");
            strSql.Append(" where ((to_number(" + startNo + ") between to_number(StartNo) and to_number(EndNo))");
            strSql.Append(" or (to_number(" + endNo + ") between to_number(StartNo) and to_number(EndNo))");
            strSql.Append(" or (to_number(StartNo) between to_number(" + startNo + ") and to_number(" + endNo + ")))");
            strSql.Append(" and SeparateId not in (select ID from cardmaking_cardseparate where Issubmit=4)");//过滤审批未通过的离盒操作信息
            if (SpId != "")
            {
                strSql.Append(" and SeparateId!='" + SpId + "'");
            }
            DataTable dt = DbHelperSQL.GetQueryResult(strSql.ToString());
            if (dt != null && dt.Rows.Count > 0)
            {
                if (int.Parse(dt.Rows[0][0].ToString()) > 0)
                    return true;
            }
            return false;
        }
    }
}
